package com.two.screen.water.balance.net.socket;

import android.os.Handler;
import android.os.Looper;

import androidx.annotation.Nullable;

import com.two.screen.water.balance.utils.CommUtils;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;


public class AutoReconnectWebSocketListener extends WebSocketListener {

    private final OkHttpClient client;
    private final Request      request;
    private       WebSocket    webSocket;
    private       long         reconnectInterval = 3000; // 重连间隔时间，这里设置为3秒
    private       int          connectTimes      = 1;//重连次数
    private       Handler      mHandler          = new Handler(Looper.myLooper());

    public AutoReconnectWebSocketListener(OkHttpClient client, Request request) {
        this.client = client;
        this.request = request;
    }

    @Override
    public void onOpen(WebSocket webSocket, okhttp3.Response response) {
        d("onOpen->response:" + response.toString());
        this.webSocket = webSocket;
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        d("onMessage->text:" + text);
        // 处理接收到的消息
    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        d("onMessage->ByteString:" + bytes);
    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        d("onClosing");
        webSocket.close(1000, null);
        reconnect();
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
        d("正在第" + connectTimes + "次重连...");
        t.printStackTrace(); // 打印错误信息
        reconnect();
    }

    private void reconnect() {
        connectTimes = connectTimes + 1;
        if (webSocket != null) {
            // 确保webSocket已关闭
            webSocket.close(1000, null);
        }
        // 开始计时重连
        mHandler.postDelayed(() -> {
            try {
                webSocket = client.newWebSocket(request, AutoReconnectWebSocketListener.this);
                // 重置重连间隔时间，根据需要调整
                reconnectInterval = 3000;
            } catch (Exception e) {
                e.printStackTrace();
                // 如果失败，则增加重连间隔时间，并继续重连
                reconnectInterval = Math.min(30000, reconnectInterval * 2);
                reconnect();
            }
        }, reconnectInterval);
    }


    private void d(String msg) {
        CommUtils.Companion.println("WebSocket->AutoReconnectWebSocketListener->", msg);
    }
}